package net.jingkao.app.common;

import java.io.File;
import java.util.Map;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

/**
 * 位图管理器
 * @author chao
 *
 */
public class BitmapManager {

	public final static String imageCachePath = "/images/";
	public final static String appPath = "/typhoon-forecast";

	private static File getImageCacheDir() {
		File cacheFile = new File(getAppPath() + imageCachePath);
		if (!cacheFile.exists()) {
			cacheFile.mkdirs();
		}
		return cacheFile;
	}

	private static Bitmap loadImageFromNet(String url,
			Map<String, Object> params, String cacheKey) {
		byte[] data = WebClient.httpGet(url, params);
		if (data == null || data.length == 0) {
			return null;
		}
		if (StringUtils.isNotEmpty(cacheKey)) {
			File cacheFile = new File(getImageCacheDir(), cacheKey);
			FileUtils.writeToFile(cacheFile, data);
		}
		return BitmapFactory.decodeByteArray(data, 0, data.length);
	}

	private static Bitmap loadImageFromLocal(String cacheKey) {
		File cacheFile = new File(getImageCacheDir(), cacheKey);
		byte[] data = FileUtils.readFromFile(cacheFile);
		if (data == null || data.length == 0) {
			return null;
		}
		return BitmapFactory.decodeByteArray(data, 0, data.length);
	}

	public static Bitmap loadImage(String url, Map<String, Object> params,
			String cacheKey) {
		Bitmap bitmap = null;
		if (StringUtils.isNotEmpty(cacheKey)) {
			bitmap = loadImageFromLocal(cacheKey);
		}
		if (bitmap != null) {
			return bitmap;
		}
		return loadImageFromNet(url, params, cacheKey);
	}
	
	public static void clear(){
		File dir = getImageCacheDir();
		for(File f : dir.listFiles()){
			f.delete();
		}
	}
	
	public static long getCacheSize(){
		File dir = getImageCacheDir();
		long size = 0;
		for(File f : dir.listFiles()){
			size += f.length();
		}
		return size;
	}
	
	public static String getAppPath(){
		String storageState = Environment.getExternalStorageState();		
		if(storageState.equals(Environment.MEDIA_MOUNTED)){
			String savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + appPath;
			File file = new File(savePath);
			if(!file.exists()){
				file.mkdirs();
			}
			return savePath;
		}else{
			return null;
		}
	}
}
